﻿var XZQDATAARRAY;//行政区数据数组
var newXZQDATAARRAY = new Array();//重排之后的数组
function XzqManage(xzqListid) {
    var manageNode = getNodeByID(xzqListid);
    getNodeByID("layerList").style.display = "none";
    var manageBodyNode = getNodeByID("XZQList_body");
    var changeresult = changeNodeState(manageNode);
    if (changeresult) {
        XZQList_body.innerHTML = "";
        if (XZQDATAARRAY == "undefind" || XZQDATAARRAY==undefined) {
            //初始化行政区列表
            readXZQListFromDatabase();
        }
        var YJ = rankXZQHGetYJ(XZQDATAARRAY);

        for (var key in YJ) {
            var newYJdiv = document.createElement("div");
            newYJdiv.id = "YJ_" + key;
            newYJdiv.style = "position:relative;left:10px;"

            //一级目录文字
            var newYJhead = document.createElement("span");
            newYJhead.className = "XZQHtree";
            newYJhead.name = key + "_" + YJ[key];
            newYJhead.onclick = function (evt) {
                catalogTreeClick(evt.target);
            }
            var showkey = key;
            if (showkey.length < 6) {
                for (var i = 0; i < (6 - (key.length)) ; i++) {
                    showkey += "0";
                }
            }
            newYJhead.innerHTML = suojin(key.length) + "<i class='fa fa-caret-right'></i>&nbsp"
            newYJhead.innerHTML += YJ[key] + "(" + showkey + ")";
            newYJdiv.appendChild(newYJhead);

            //一级目录点击按钮
            var newYJbtn = document.createElement("span");
            newYJbtn.innerHTML = "&nbsp&nbsp<i class='fa fa-map-marker' title='定位' style='cursor: pointer;' onclick=positionByXZQHDM('" + key + "')></i>";
            newYJdiv.appendChild(newYJbtn);

            manageBodyNode.appendChild(newYJdiv);
        }
    }
}

//定位
function positionByXZQHDM(XZQHDM) {
    var levelName = checkLevel(XZQHDM)[1];
    if (levelName == 0) {
        alert("缺少定位信息");
        return;
    }
    var LevelInfo = m_config_levelsInfo[levelName];
    var queryField = LevelInfo["strQueryFiled"];
    var serverUrl = LevelInfo["strServerUrl"];
    var layerName = LevelInfo["strLayer"];
    var serverType = LevelInfo["strServerType"];
    var color = LevelInfo["strColor"];
    var showkey = XZQHDM;
    if (showkey.length < 6) {
        for (var i = 0; i < (6 - (XZQHDM.length)) ; i++) {
            showkey += "0";
        }
    }
    if (serverType=="geoserver") {
        var parm = {};
        parm[queryField] = showkey;
        var options = {
            url: serverUrl,
            layer: layerName,
            where: parm
        }
        var query = new queryGeoserver(options);
        var result = query.query();

        var resultProjInfos = result.crs.properties.name.split(":");
        var resultProj = resultProjInfos[resultProjInfos.length - 1];
        if (resultProj != 3857) {
            resultProj = 4326;
        }

        //要素显示
        var geometry = result.features[0].geometry;
        var arr = new Array();
        var mapprojection = map.getView().getProjection().code_;

        arr[0] = changeCoord(geometry.coordinates[0][0], "EPSG:" + resultProj, mapprojection);

        var polygon = new ol.geom.Polygon(arr); //geometry.coordinates[0]
        var feature = new ol.Feature({
            geometry: polygon
        });
        var style = new ol.style.Style({
            stroke: new ol.style.Stroke({
                color: color,
                width: 4
            })
        })
        feature.setStyle(style);
        marksource.clear();
        marksource.addFeature(feature);

        var extent = marksource.getExtent();



        //结果定位
        map.getView().fit(extent, {
            duration: 1000
        });
    }
    console.log(LevelInfo);
}

//行政区目录点击
function catalogTreeClick(node) {
    var nodeNames = node.name.split("_");
    if (nodeNames[2]) {
        node.parentNode.parentNode.removeChild(node.parentNode.nextSibling);
        var index = node.name.lastIndexOf("_");
        node.name = node.name.slice(0, index);
        node.getElementsByTagName("i")[0].className = "fa fa-caret-right";
        return;
    }
    node.name += "_isopen";
    node.getElementsByTagName("i")[0].className = "fa fa-caret-down";
    var nodeName = nodeNames[0];
    var nodeInnerHTML = nodeNames[1];
    //var newSublingNode = document.createElement("div");
    var DJList = {};
    if (nodeName.length<6) {
        DJList = getLowerXZQDJ(nodeName, 2);
    }
    else if (nodeName.length < 12) {
        DJList = getLowerXZQDJ(nodeName, 3);
    }
    else {
        DJList = getLowerXZQDJ(nodeName, 7);
    }

    //添加子节点div
    var DJdiv = document.createElement("div");
    $(node.parentNode).after(DJdiv);

    //如果子节点为空时
    if (DJList == null) {
        var newdiv = document.createElement("div");
        //标题
        var newhead = document.createElement("div");
        newhead.className = "XZQHtree";
        newhead.innerHTML = suojin(nodeName.length + 2);
        newhead.innerHTML += nodeInnerHTML;
        newdiv.appendChild(newhead);
        DJdiv.appendChild(newdiv);
        return;
    }

    for (var key in DJList) {
        var newdiv = document.createElement("div");
        //低级标题
        var newhead = document.createElement("span");
        newhead.name = key + "_" + DJList[key]["FD_VALUE"];
        newhead.className = "XZQHtree";
        if (key.length<12) {
            newhead.onclick = function (evt) {
                catalogTreeClick(evt.target);
            }
        }
        var showkey = key;
        if (showkey.length <= 9) {
            for (var i = 0; i < (6 - (key.length)) ; i++) {
                showkey += "0";
            }
            newhead.innerHTML = suojin(key.length) + "<i class='fa fa-caret-right'></i>&nbsp";
            newhead.innerHTML += (DJList[key]["FD_VALUE"] + "(" + showkey + ")");
        }
        else if (showkey.length > 6) {
            if (showkey.length <= 9) {
                newhead.innerHTML = suojin(key.length) + "<i class='fa fa-caret-right'></i>&nbsp";
                newhead.innerHTML += DJList[key]["FD_VALUE"];
            }
            else {
                newhead.innerHTML = suojin(key.length);
                newhead.innerHTML += DJList[key]["FD_VALUE"];
            }
        }
        newdiv.appendChild(newhead);
        //低级目录点击按钮
        var newDJbtn = document.createElement("span");
        newDJbtn.innerHTML = "&nbsp&nbsp<i class='fa fa-map-marker' title='定位' style='cursor: pointer;' onclick=positionByXZQHDM('" + key + "')></i>";
        newdiv.appendChild(newDJbtn);

        DJdiv.appendChild(newdiv);
    }
}

//缩进
function suojin(strLength) {
    var str = "";
    for (var i = 0; i < strLength; i++) {
        str += "&nbsp&nbsp";
    }
    return str;
}

//读取数据库获取行政区划内容
function readXZQListFromDatabase() {
    $.ajax({
        type: "post",
        async: false,
        url: "/PZ1.ashx",
        data: //发送到服务器的参数
            {
                stype: "getXZQList"
            },
        datatype: "json",
        success: function (result) {
            XZQDATAARRAY = changeStrToJson(result);
        },
        error: function (err) {
            if (err.status == 405)
                top.location.href = '/';
        }
    });
}

//根据ID获取页面节点
function getNodeByID(nodeID) {
    return document.getElementById(nodeID);
}

//改变节点显示状态  显示or不显示
function changeNodeState(node) {
    if (node.style.display=="none") {
        node.style.display = "";
        return true;
    }
    else {
        node.style.display = "none";
        return false;
    }
}

//将后台返回结果字符串转为json对象
function changeStrToJson(str) {
    var arr = new Array();
    result = str.slice(2, str.length - 2);
    var resultsStr = result.split("},{");
    for (var i = 0; i < resultsStr.length; i++) {
        var jsonStr = "{" + resultsStr[i] + "}";
        var resultJSON = JSON.parse(jsonStr);
        arr.push(resultJSON);
    }
    return arr;
}

//将获取到的行政区数据按照行政区划关系整理
function rankXZQHGetYJ(dataArr) {
    var reg = /^[0]*$/;
    var YJ = {};
    for (var i = 0; i < dataArr.length; i++) {
        var FD_CODE = myTrim(dataArr[i].FD_CODE);
        var FD_VALUE = dataArr[i].FD_VALUE;
        var newarr = new Array();
        newarr = [FD_CODE.slice(0, 2), FD_CODE.slice(2, 4), FD_CODE.slice(4, 6), FD_CODE.slice(6, 9), FD_CODE.slice(9, 12), FD_CODE.slice(12), FD_CODE, FD_VALUE];
        if (reg.test(FD_CODE.slice(2))) {
            YJ[newarr[0]] = FD_VALUE;
        }
        newXZQDATAARRAY.push(newarr);
    }
    return YJ;
}

//获取低级行政区划
function getLowerXZQDJ(str, djLength) {
    var nowlevel = checkLevel(str)[0];
    if (nowlevel + 1 > parseInt(m_loadLevel["loadLevel"])) {
        return null;
    }
    var strLength = str.length+djLength;
    var reg = /^[0]*$/;//测试字符串是否为0
    var DJ = {};
    var hasValue = false;
    for (var i = 0; i < XZQDATAARRAY.length; i++) {
        var FD_CODE = XZQDATAARRAY[i]["FD_CODE"];
        var FD_VALUE = XZQDATAARRAY[i]["FD_VALUE"];
        var strSlice0 = FD_CODE.slice(0, str.length);
        var strSlice1 = FD_CODE.slice(0, strLength);
        var strSlice2 = FD_CODE.slice(strLength);
        if (str == strSlice0) {
            if (str.length > 11) {
                DJ[strSlice1] = XZQDATAARRAY[i];
                hasValue = true;
            }
            else {
                if (reg.test(strSlice2) && !(reg.test(strSlice1.slice(str.length)))) {
                    DJ[strSlice1] = XZQDATAARRAY[i];
                    hasValue = true;
                }
            }
        }
        else {
            continue;
        }
    }
    if (hasValue) {
        return DJ;
    }
    else {
        return null;
    }
    
}

//删除字符串两端空格
function myTrim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

//判断代码等级
function checkLevel(strXZQHDM) {
    var nowlevel = 0;
    var arr = new Array();
    switch (strXZQHDM.length) {
        case 2: arr = [1, "sheng"];
            break;
        case 4: arr = [2, "shi"];
            break;
        case 6: arr = [3, "xian"];
            break;
        case 9:  arr = [4, "xiang"];
            break;
        case 12:  arr = [5, "cun"];
            break;
        default:
            nowlevel = [0, 0];
            break;
    }
    return arr;
}